package com.biglead.admin.controller;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.biglead.admin.api.CommonResult;
import com.biglead.admin.param.AdminAuthParam;
import com.biglead.feign.clients.FeignAuthClient;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 后台用户登录
 */
@Controller
@Slf4j
@RequestMapping("/admin")
public class AdminAuthController {

    @Autowired
    private FeignAuthClient feignAuthClient;
    /**
     * 登录以后返回token
     * @return
     */
    @PostMapping(value = "/login")
    @ResponseBody
    public CommonResult login(@Validated @RequestBody AdminAuthParam authParam) {

        String username = authParam.getUsername();
        String password = authParam.getPassword();
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            return CommonResult.failed("请输入用户名和密码");
        }

        MultiValueMap<String,String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type","multipart/form-data");
        headers.add("Authorization","Basic WGNXZWJBcHA6WGNXZWJBcHA=");

        MultiValueMap<String,String> body = new LinkedMultiValueMap<>();
        body.add("username",username);
        body.add("password",password);
        body.add("grant_type","password");
        body.add("scope","all");

        //服务内部调用 认证服务
        Map<String,Object>  map = feignAuthClient.generateToken(body);

        log.info("获取token成功 {}",map);
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("token", map.get("access_token"));
        tokenMap.put("tokenHead", "");
        return CommonResult.success(tokenMap);
    }

    @ApiOperation(value = "登出功能")
    @PostMapping(value = "/logout")
    @ResponseBody
    public CommonResult logout() {
        return CommonResult.success(null);
    }
}
